//
//  OMGWebViewViewController.m
//  A_project2.0
//
//  Created by Tiny on 16/3/10.
//  Copyright © 2016年 七平. All rights reserved.
//

#import "OMGWebViewViewController.h"
#import "CollectionWebViewModel.h"

#import "WeiboSDK.h"
#import "WeiboSDK+Statistics.h"
#import "AppDelegate.h"

@interface OMGWebViewViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) NSString *webtitle;
@property (nonatomic, strong) QP_HUD *HUD;
@end

@implementation OMGWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /**< 设置导航栏标题 */
    self.navigationItem.title = @"详情";
    
    UIWebView *wv = [[UIWebView alloc]initWithFrame:self.view.bounds];
    /**< 自适应边界 */
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view addSubview:wv];
    /**< js */
    wv.scalesPageToFit = YES;
    wv.delegate = self;
    NSURL *url = [[NSURL alloc]initWithString:self.urlStr];
    NSURLRequest *request =  [[NSURLRequest alloc] initWithURL:url];
    [wv loadRequest:request];
    /**< 调用菊花类 */
    self.HUD = [[QP_HUD alloc]initWithFrame:self.view.frame];
    [self.view addSubview:_HUD];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _HUD.hidden = YES;
    self.webtitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    UIBarButtonItem *collection = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-shoucang"] style:UIBarButtonItemStylePlain target:self action:@selector(shoucang)];
    UIBarButtonItem *fenxiang = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(fenxiang)];
    
    self.navigationItem.rightBarButtonItems = @[collection, fenxiang];
    

}

- (void)fenxiang
{
    NSLog(@"分享");
    
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    
    [WeiboSDK sendRequest:request];

}

- (WBMessageObject *)messageToShare //分享消息到新浪微博
{
    WBMessageObject *message = [WBMessageObject message];
    
    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.objectID = @"identifier1";
    webpage.title = NSLocalizedString(_webtitle, nil);
    webpage.description = [NSString stringWithFormat:NSLocalizedString(@"分享到新浪微博", nil), [[NSDate date] timeIntervalSince1970]];
    //     webpage.thumbnailData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_1" ofType:@"jpg"]];
    //    webpage.webpageUrl = self.urlStr;
    //    message.mediaObject = webpage;
    message.text =  [NSString stringWithFormat:@"%@ %@", _webtitle, _urlStr];
    
    return message;
}


- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    NSString *title = nil;
    UIAlertView *alert = nil;
    
    title = NSLocalizedString(@"收到网络回调", nil);
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",result]
                                      delegate:nil
                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
                             otherButtonTitles:nil];
    [alert show];
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    NSString *title = nil;
    UIAlertView *alert = nil;
    
    title = NSLocalizedString(@"请求异常", nil);
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",error]
                                      delegate:nil
                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
                             otherButtonTitles:nil];
    [alert show];
}














- (void)shoucang
{
    /**< 复杂对象写本地 */
    CollectionWebViewModel *p = [[CollectionWebViewModel alloc]init];
    p.title = _webtitle;
    p.urlStr = _urlStr;
    // 归档
    // 1. 获取路径
    // 写本地的文件后缀没有任何影响
    NSString *collectionPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"collectionWebView.txt"];
    // 先获取
    NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:collectionPath];
    // 数组存在 直接添加
    if (arr) {
        for (CollectionWebViewModel *p in arr) {
            if ([p.title isEqualToString:self.webtitle]) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已经收藏" message:@"请到我的收藏中查看" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                [self performSelector:@selector(diss) withObject:self afterDelay:1];
                return;
            }
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        [arr addObject:p];
    }else{
        arr = [NSMutableArray array];
        [arr addObject:p];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"收藏成功2" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
    }
    // 归档
    [NSKeyedArchiver archiveRootObject:arr toFile:collectionPath];
}
- (void)diss
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
